package com.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.hibernate.HibernateDao;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.entity.RuleClass;

@Transactional
@Component
public class RclassDao extends HibernateDao {

	@Resource
	SessionFactory sessionFactory;

	public List<RuleClass> loadRuleClassParent() {
		String hql = "from RuleClass where parentId is null";
		return this.query(hql);
	}

	public List<RuleClass> loadRuleClassChild(String parentId) {
		String hql = "from RuleClass where parentId=:parentId";
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("parentId", parentId);
		return this.query(hql, parameter);
	}

	public boolean checkRuleClassHaveChild(String id) {
		String hql = "from RuleClass where parentId=:id";
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("id", id);
		return this.query(hql, parameter).size() > 0 ? true : false;
	}

	public void saveClass(List<RuleClass> ruleClass) {
		for (RuleClass rClass : ruleClass) {
			if (EntityState.NEW.equals(EntityUtils.getState(rClass))) {
				rClass.setCreateDate(new Date());
				rClass.setCreateUser(ContextHolder.getLoginUserName());
				sessionFactory.getCurrentSession().save(rClass);
			} else if (EntityState.MODIFIED.equals(EntityUtils.getState(rClass))) {
				rClass.setUpdateDate(new Date());
				rClass.setUpdateUser(ContextHolder.getLoginUserName());
				sessionFactory.getCurrentSession().update(rClass);
			} else if (EntityState.DELETED.equals(EntityUtils.getState(rClass))) {
				sessionFactory.getCurrentSession().delete(rClass);
			} else if (EntityState.NONE.equals(EntityUtils.getState(rClass))) {
				if (rClass.getChildren() != null) {
					this.saveClass(rClass.getChildren());
				}
			}
		}
	}

}
